package se.djupfeldt.oscar.logbook.utils;

import java.util.concurrent.LinkedBlockingQueue;

public class CircularQueue<T> {
    LinkedBlockingQueue<T> buffer;
    
    public CircularQueue(int size) {
	buffer = new LinkedBlockingQueue<T>(size);
    }
    
    public boolean add(T object) {
	if (buffer.offer(object)) {
	    return true;
	} else {
	    buffer.poll();
	    return add(object);
	}
    }
    
    public T peek() {
	return buffer.peek();
    }
    
    @SuppressWarnings("unchecked")
    public T getLatest() {
	Object[] arr = buffer.toArray();
	if (arr.length == 0)
	    return null;
	return (T) arr[arr.length - 1];
    }
    
    public Object[] toArray() {
	return buffer.toArray();
    }
    
    public T[] toArray(T[] array) {
	return buffer.toArray(array);
    }
    
    public int size() {
	return buffer.size();
    }
    
    @Override
    public String toString() {
        return buffer.toString();
    }
}
